<?php
class Model_user extends CI_Model{
    function validate(){
        $username = $this->input->post('username');
        $password = md5($this->input->post('password'));
        $q1 = $this->db->query("SELECT * FROM admin WHERE username='$username' AND password='$password'");
        $q2 = $this->db->query("SELECT * FROM guru WHERE nip='$username' AND password='$password'");
        $q3 = $this->db->query("SELECT * FROM siswa WHERE nim='$username' AND password='$password'");
        
        if($q1->num_rows == 1){
            $row = $q1->row();
            $creds = array(
                'type' => 'admin',
                'nama' => $row->username
            );
            $this->session->set_userdata($creds);
        }else if($q2->num_rows == 1){
            $row = $q2->row();
            $creds = array(
                'type' => 'guru',
                'id' => $row->id,
                'nip' => $row->nip,
                'nama' => $row->nama
            );
            $this->session->set_userdata($creds);
        }else if($q3->num_rows == 1){
            $row = $q3->row();
            $creds = array(
                'type' => 'siswa',
                'id' => $row->id,
                'nim' => $row->nim,
                'nama' => $row->nama,
                'kelas' => $row->kelas
            );
            $this->session->set_userdata($creds);
        }else{
            $creds = null;
        }
        
        return $creds;
    }
    
    function auth() {
        if (isset($this->session->userdata['type'])) {
            if ($this->session->userdata['type'] == 'admin') {
                $authenticated = 1;
            } else if ($this->session->userdata['type'] == 'guru') {
                $authenticated = 1;
            } else if ($this->session->userdata['type'] == 'siswa') {
                $authenticated = 1;
            } else {
                $authenticated = 0;
            }
        } else {
            $authenticated = 0;
        }
        
        return $authenticated;
    }
}
?>
